import {
  addAddress,
  getAddress,
  updateAddress,
  deleteAddress,
} from "@/Api/address";
const state = {
  curModifyAddress: {},
  addressList: [],
};
const mutations = {
  ADD_ADDRESS_LIST(state, list) {
    if (list.length > 0) {
      let index = list.findIndex((item) => {
        return item.isDefault == "true";
      });
      let temp = list[index];
      list.splice(index, 1);
      list.unshift(temp);
    }
    state.addressList = list;
  },
  SET_CUR_ADDRESS(state, value) {
    state.curModifyAddress = value;
  },
};
const actions = {
  async deleteAddress(context, id) {
    let result = await deleteAddress(id);
    console.log(result);
    if (result.data.status == 200) {
      context.dispatch("getAddress");
      return "success";
    } else return "error";
  },
  async updateAddress(context, data) {
    data.isDefault = String(data.isDefault);
    data.address = data.address + "__" + data.detailadd;
    delete data.detailadd;
    let result = await updateAddress(data);
    console.log(result);
    if (result.data.status == 200) {
      context.dispatch("getAddress");
      return "success";
    } else return "error";
  },
  async addAddress(context, data) {
    data.address = data.address + "__" + data.detailadd;
    data.isDefault = String(data.isDefault);
    delete data.detailadd;
    let result = await addAddress(data);
    console.log(result);
    if (result.data.status == 200) {
      context.dispatch("getAddress");
      return "success";
    } else return "error";
  },
  async getAddress({ commit }) {
    let result = await getAddress();
    console.log(result);
    if (result.data.status == 200) {
      if (result.data.data.length > 0) {
        result.data.data.forEach((item) => {
          let arr = item.address.split("__");
          item.address = arr[0];
          item.detailadd = arr[1];
        });
      }
      commit("ADD_ADDRESS_LIST", result.data.data);
      return "success";
    } else {
      return "error";
    }
  },
};
const getters = {
  addressList(state) {
    let data = state.addressList;
    console.log(data);
    if (data.length == 0) {
      return data || [];
    }
    console.log(data);
    let index = data.findIndex((item) => {
      return item.isDefault == "true";
    });
    console.log(index);
    let temp = data[index];
    data.splice(index, 1);
    data.unshift(temp);
    console.log(data);
    return data || [];
  },
  getCurAddress(state) {
    return state.curModifyAddress || {};
  },
};

export default {
  state,
  mutations,
  actions,
  getters,
};
